﻿using System;
using System.Collections.Generic;
using Battle.Common;
using CardGameCore.Common;


namespace CardGameCore.Battle
{
    public class BattleInitialize : IBattleInitialize
    {
        private readonly IDataProvider _dataProvider;
        private readonly IBattlefield _battlefield;
        private readonly IBattleSettings _battleSettings;
        
        public BattleInitialize(
            IDataProvider dataProvider,
            IBattlefield battlefield,
            IBattleSettings battleSettings)
        {
            _dataProvider = dataProvider;
            _battlefield = battlefield;
            _battleSettings = battleSettings;
        }

        public void Initialize()
        {
            var player = new Player()
            {
                MaxHp = _dataProvider.BattleData.PlayerHp,
                Hp = _dataProvider.BattleData.PlayerHp,
            };
            var enemy = new Enemy()
            {
                MaxHp = _dataProvider.BattleData.EnemyHp,
                Hp = _dataProvider.BattleData.EnemyHp
            };
            
            ProcessCard(player.CardPool, _dataProvider.BattleData.PlayerCards);
            ProcessCard(enemy.CardPool, _dataProvider.BattleData.EnemyCards);
            ProcessBattlePosition(player.Positions);
            ProcessBattlePosition(enemy.Positions);
            _battlefield.Init(player, enemy, _battleSettings.InitialCost);
        }

        private void ProcessCard(ICollection<Card> container, IEnumerable<int> source)
        {
            foreach (var id in source)
            {
                if (!_dataProvider.CardDataDictionary.ContainsKey(id))
                {
                    throw new Exception("Data Exception");
                }

                var cardData = _dataProvider.CardDataDictionary[id];
                var card = new Card()
                {
                    Hp = cardData.Hp,
                    MaxHp = cardData.Hp,
                    Attack = cardData.Attack
                };
                container.Add(card);
            }
        }

        private static void ProcessBattlePosition(ICollection<Vector2Int> positions)
        {
            //todo
            positions.Add(new Vector2Int(0, 0));
            positions.Add(new Vector2Int(1, 0));
            positions.Add(new Vector2Int(0, 1));
            positions.Add(new Vector2Int(1, 1));
            positions.Add(new Vector2Int(0, 2));
            positions.Add(new Vector2Int(2, 2));
        }
    }
}